/**
 * 通知状态管理
 */
import { defineStore } from 'pinia'
import { ref, computed } from 'vue'

export const useNotificationsStore = defineStore('notifications', () => {
  // 状态
  const notifications = ref([])
  const unreadCount = ref(0)
  const isConnected = ref(false)
  const lastSyncTime = ref(null)

  // 计算属性
  const unreadNotifications = computed(() => 
    notifications.value.filter(notification => !notification.isRead)
  )

  const recentNotifications = computed(() => 
    notifications.value
      .sort((a, b) => b.timestamp - a.timestamp)
      .slice(0, 10)
  )

  const notificationsByCategory = computed(() => {
    const categories = {}
    notifications.value.forEach(notification => {
      const category = notification.category || 'general'
      if (!categories[category]) {
        categories[category] = []
      }
      categories[category].push(notification)
    })
    return categories
  })

  const highPriorityNotifications = computed(() => 
    notifications.value.filter(notification => 
      notification.priority === 'high' || notification.priority === 'urgent'
    )
  )

  // 动作
  const addNotification = (notification) => {
    // 检查是否已存在相同ID的通知
    const existingIndex = notifications.value.findIndex(n => n.id === notification.id)
    
    if (existingIndex > -1) {
      // 更新现有通知
      notifications.value[existingIndex] = {
        ...notifications.value[existingIndex],
        ...notification,
        timestamp: Date.now()
      }
    } else {
      // 添加新通知
      notifications.value.unshift({
        id: notification.id || `notif_${Date.now()}`,
        title: notification.title || '新通知',
        content: notification.content || '',
        type: notification.type || 'info',
        priority: notification.priority || 'normal',
        category: notification.category || 'general',
        sender: notification.sender,
        timestamp: notification.timestamp || Date.now(),
        isRead: notification.isRead || false,
        data: notification.data || {},
        createdAt: Date.now()
      })
    }
    
    // 限制通知数量，保留最新的100条
    if (notifications.value.length > 100) {
      notifications.value = notifications.value.slice(0, 100)
    }
    
    updateUnreadCount()
  }

  const removeNotification = (notificationId) => {
    const index = notifications.value.findIndex(n => n.id === notificationId)
    if (index > -1) {
      notifications.value.splice(index, 1)
      updateUnreadCount()
    }
  }

  const markAsRead = (notificationId) => {
    const notification = notifications.value.find(n => n.id === notificationId)
    if (notification && !notification.isRead) {
      notification.isRead = true
      notification.readAt = Date.now()
      updateUnreadCount()
    }
  }

  const markAllAsRead = () => {
    notifications.value.forEach(notification => {
      if (!notification.isRead) {
        notification.isRead = true
        notification.readAt = Date.now()
      }
    })
    updateUnreadCount()
  }

  const updateNotificationReadStatus = (notificationId, isRead) => {
    const notification = notifications.value.find(n => n.id === notificationId)
    if (notification) {
      notification.isRead = isRead
      if (isRead) {
        notification.readAt = Date.now()
      }
      updateUnreadCount()
    }
  }

  const updateUnreadCount = () => {
    unreadCount.value = notifications.value.filter(n => !n.isRead).length
  }

  const clearAllNotifications = () => {
    notifications.value = []
    unreadCount.value = 0
  }

  const clearReadNotifications = () => {
    notifications.value = notifications.value.filter(n => !n.isRead)
    updateUnreadCount()
  }

  const setConnectionState = (connected) => {
    isConnected.value = connected
  }

  const updateLastSyncTime = () => {
    lastSyncTime.value = Date.now()
  }

  const getNotificationById = (notificationId) => {
    return notifications.value.find(n => n.id === notificationId)
  }

  const getNotificationsByCategory = (category) => {
    return notifications.value.filter(n => n.category === category)
  }

  const getNotificationsByPriority = (priority) => {
    return notifications.value.filter(n => n.priority === priority)
  }

  const getNotificationsByType = (type) => {
    return notifications.value.filter(n => n.type === type)
  }

  const searchNotifications = (query) => {
    const lowerQuery = query.toLowerCase()
    return notifications.value.filter(notification => 
      notification.title.toLowerCase().includes(lowerQuery) ||
      notification.content.toLowerCase().includes(lowerQuery) ||
      (notification.sender && notification.sender.username && 
       notification.sender.username.toLowerCase().includes(lowerQuery))
    )
  }

  const getNotificationsInTimeRange = (startTime, endTime) => {
    return notifications.value.filter(notification => 
      notification.timestamp >= startTime && notification.timestamp <= endTime
    )
  }

  const exportNotifications = () => {
    return {
      notifications: notifications.value,
      exportTime: Date.now(),
      totalCount: notifications.value.length,
      unreadCount: unreadCount.value
    }
  }

  const importNotifications = (data) => {
    if (data && data.notifications && Array.isArray(data.notifications)) {
      notifications.value = data.notifications
      updateUnreadCount()
      updateLastSyncTime()
    }
  }

  // 初始化
  const initialize = () => {
    // 从localStorage加载通知
    const savedNotifications = localStorage.getItem('notifications')
    if (savedNotifications) {
      try {
        const parsed = JSON.parse(savedNotifications)
        if (parsed.notifications && Array.isArray(parsed.notifications)) {
          notifications.value = parsed.notifications
          updateUnreadCount()
        }
      } catch (error) {
        console.error('❌ 加载通知数据失败:', error)
      }
    }
  }

  // 保存到localStorage
  const saveToLocalStorage = () => {
    try {
      localStorage.setItem('notifications', JSON.stringify({
        notifications: notifications.value,
        lastSyncTime: lastSyncTime.value
      }))
    } catch (error) {
      console.error('❌ 保存通知数据失败:', error)
    }
  }

  // 监听通知变化，自动保存
  const saveNotifications = () => {
    saveToLocalStorage()
  }

  return {
    // 状态
    notifications,
    unreadCount,
    isConnected,
    lastSyncTime,
    
    // 计算属性
    unreadNotifications,
    recentNotifications,
    notificationsByCategory,
    highPriorityNotifications,
    
    // 动作
    addNotification,
    removeNotification,
    markAsRead,
    markAllAsRead,
    updateNotificationReadStatus,
    updateUnreadCount,
    clearAllNotifications,
    clearReadNotifications,
    setConnectionState,
    updateLastSyncTime,
    getNotificationById,
    getNotificationsByCategory,
    getNotificationsByPriority,
    getNotificationsByType,
    searchNotifications,
    getNotificationsInTimeRange,
    exportNotifications,
    importNotifications,
    initialize,
    saveToLocalStorage,
    saveNotifications
  }
})
